package cli.menu;

/**
 * BudgetBuoy
 * 
 * Simplify your personal expense management
 * 
 * @team cs2103jan13-w15-3j
 */

//--------------------------------------------------------------

/**
 * SearchByName Class
 * 
 * Description: 
 * 
 * 
 * @package   cli.menu
 * @author    Lai Yong Quan (A0080909Y)
 * @editor(s) -
 */
import shared.*;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import cli.tools.*;

class SearchByName extends Function{
	
	private static final String[] reqInput = {
		"-= Main menu > Search > Search by Name =-",
		"",
		"Enter the name you would like to search: "
	};
	
	private static final String[] selectItem = {
		"-= Main menu > Search > Search by Name =-",
		"[b]: back [u]: undo [r]: redo [h]: home menu",
		"",
		"Select an item to view in detail by keying in its index"
	};
	
	
	
	private static final State back = State.SEARCHSELECTFILTER;
	private static final State current = State.SEARCHBYNAME;
	
	
	public static State runMenu(){
		cli.print(reqInput);
		State nextState = current;
		
		String input = cli.nextLine();
		
		List<Record> searchResults = null;
		SortedSet<Record> results = null;
		try{
		results = cli.getApi().getNameRange(input);
		}
		catch(Exception e){
			cli.print(noResults);
			return back;
		}
		

	if ((results == null)|| results.isEmpty()){
		cli.print(noResults);
		return back;
	}
	
//	cli.print(selectItem);
	
	// converts sortedset to an arry to a list
			Record[] temp = results.toArray(new Record[1]);
			searchResults = new ArrayList<Record>();
			for (int i = 0; i < temp.length; i++)
				searchResults.add(temp[i]);
			
			
			Object choice = tools.selectFromList(searchResults, "searchByName", selectItem);
			
			// if user selected back
			if (choice == null) {
				// go back to searchSelectFilter
				return back;
			}

			// if user's choice diverts to another menu (e.g, home)
			if (choice.getClass() == State.class) {
				return (State) choice;
			}

			// if user selected a good choice
			Record toView = (Record) choice;
			Access.viewRecord(toView);
			Access.modifyRecord(toView);
			
			return nextState;
			

	}
}